% function for calculating market shares as a fraction of previous market
% shares, allowing for some growth in the market size
% incorporates ideas from code in PBM paper

function shares = demand(delta, gamma , prev_shares, g)

    N = length(delta);
    
    % can tack on an outside option (delta = 0; copay = 0)
    prev_shares = [prev_shares/(1+g); (1-sum(prev_shares)+g)/(1+g)];
    
    %% For each group
    % compute beta * X, exponentiate, sum, normalize
    share_matrix = repmat(delta,1,N);
    
    % create a square matrix (each column is based on previous choice)
    share_matrix = share_matrix + gamma;

    % need to deal with new users
    share_matrix = [share_matrix delta]; % column for new users
    share_matrix = [share_matrix; zeros(1,N+1)]; % column for outside option
    
    exp_share_matrix = exp(share_matrix);
    
    col_sum = sum(exp_share_matrix);
    col_sum = repmat(col_sum, N+1, 1);
    
    share_matrix = exp_share_matrix ./ col_sum;
    
    s = share_matrix * prev_shares;
    shares = s(1:N);
end

